package v1

import (
	"ginblog/model"
	"ginblog/utils/errormsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

var (
	codeCate int
)

// AddCategory 增加分类
func AddCategory(c *gin.Context) {
	var data model.Category
	_ = c.ShouldBindJSON(&data)
	codeCate = model.CheckCate(data.Name)
	if codeCate == errormsg.ERROR_CATENAME_USED {
		codeCate = errormsg.ERROR_CATENAME_USED
	} else if codeCate == errormsg.SUCCESS {
		model.AddCate(&data)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  codeCate,
		"message": errormsg.GetErrorMsg(codeCate),
		"data":    data,
	})
}

// FindCate 查找分类列表
func FindCate(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize")) //这里要严格规范大小写 要和前端的参数大小写一致
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1 // -1 表示不使用
	}
	if pageNum == 0 {
		pageNum = -1 // -1 表示不使用
	}
	//调用model下面的查询用户函数
	data, total := model.GetCate(pageSize, pageNum)
	codeCate = errormsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  codeCate,
		"message": errormsg.GetErrorMsg(codeCate),
		"data":    data,
		"total":   total,
	})
}

// DeleteCate 删除分类
func DeleteCate(c *gin.Context) {
	var cate model.Category
	_ = c.ShouldBindJSON(&cate)
	id, _ := strconv.Atoi(c.Param("id"))
	codeCate = model.DeleteCate(id)
	if codeCate == errormsg.ERROR {
		codeCate = errormsg.ERROR
	}
	codeCate = errormsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  codeCate,
		"message": errormsg.GetErrorMsg(codeCate),
	})
}

// UpdateCate 编辑分类
func UpdateCate(c *gin.Context) {
	//1.先进行判断传入的新的分类名称是否存在
	var cate model.Category
	_ = c.ShouldBindJSON(&cate)
	codeCate = model.CheckCate(cate.Name)
	if codeCate == errormsg.ERROR_CATENAME_USED {
		c.Abort() //中断本次修改操作的后续函数的调用
	}
	//2.进行分类信息修改操作
	id, _ := strconv.Atoi(c.Param("id"))
	if codeCate == errormsg.SUCCESS {
		codeCate = model.UpdateCate(id, &cate)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  codeCate,
		"message": errormsg.GetErrorMsg(codeCate),
	})
}
